package com.letv.app.ljodfh.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.IdRes;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.sdk.statisticssdk.StatisticsMainInit;
import com.jiongbull.jlog.JLog;
import com.letv.app.ljodfh.R;
import com.letv.app.ljodfh.base.Cache;
import com.letv.app.ljodfh.base.Constances;
import com.letv.app.ljodfh.beans.EventMessage;
import com.letv.app.ljodfh.beans.FChannel;
import com.letv.app.ljodfh.beans.TvLivingList;
import com.letv.app.ljodfh.ui.contract.ChannelContract;
import com.letv.app.ljodfh.ui.presenter.ChannelPresenter;
import com.letv.app.ljodfh.ui.util.RBaseItemDecoration;
import com.letv.app.ljodfh.ui.widget.BasePlayerView;
import com.letv.app.ljodfh.ui.widget.DisSlideViewPager;
import com.letv.app.ljodfh.utils.UserManager;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static com.letv.app.ljodfh.base.Constances.KEY_CHANGE_CHANNEL;

/**
 * 频道
 *
 * @author suming
 * @date 2020/4/13 14:21
 */
public class ChannelFragment extends ColumnBaseFragment implements ChannelContract.View, TabLayout.OnTabSelectedListener {
    private static final String TAG = ChannelFragment.class.getSimpleName();

    private static final int TYPE_CHANNEL = 190;
    private static final int TYPE_RADIO = 406;
    private static final String KEY_TYPE = "TYPE";
    private static final String KEY_DATA = "DATA";

    /////////////////// bind views ///////////////////
    @BindView(R.id.video_player)
    BasePlayerView mVideoPlayer;
    @BindView(R.id.tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.viewPager)
    DisSlideViewPager mViewPager;
    private Unbinder mBind;

    private FChannel mCurChannel;
    private LocalPagerAdapter mAdapter;
    private ChannelContract.Presenter mPresenter;
    private Handler handler = new Handler();
    private boolean isFirstStart = true;

    public static ChannelFragment newInstance() {
        Bundle args = new Bundle();
        ChannelFragment fragment = new ChannelFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_channel, container, false);
        mBind = ButterKnife.bind(this, rootView);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mPresenter = new ChannelPresenter(this);
        initView(rootView, savedInstanceState);
        return rootView;
    }

    private void initView(@Nullable View rootView, @Nullable Bundle savedInstanceState) {
        //////////////////// init video player ///////////////////////////////////////
        mVideoPlayer.getThumbImge().setImageResource(R.mipmap.icon_def_16_9_l);
        mVideoPlayer.setRotateViewAuto(false);
        mVideoPlayer.setNeedShowWifiTip(false);
        mVideoPlayer.setLooping(false);
        mVideoPlayer.setLiving(true);
        mVideoPlayer.setFullClick((player, isLandscape) -> {
            if (isLandscape) {
                actionToPortrait();
                StandardGSYVideoPlayer.backFromWindowFull(getContext());
            } else {
                actionToLandscape();
            }
        });

        JLog.e("channelUrl: " + channelUrl);
        mPresenter.fetchData();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden && null != mVideoPlayer) {
            mVideoPlayer.onVideoPause();
        }
    }



    @Override
    public void renderData(TvLivingList response) {
        /////////////////// init tab///////////////////
        if (response == null) return;
        mAdapter = new LocalPagerAdapter(getChildFragmentManager());
        mAdapter.addFragment(0, new TabItem.Builder()
                        .title("频道")
                        .defaultId(R.mipmap.icon_tv_play_normal)
                        .selectId(R.mipmap.icon_tv_play_press)
                        .build(),
                ChildChannelFragment.newInstance(TYPE_CHANNEL, (ArrayList<FChannel>) elementAtSelected(response.getChannel(), 0)));
//        mAdapter.addFragment(1, new TabItem.Builder()
//                        .title("广播")
//                        .defaultId(R.mipmap.icon_tv_fm_normal)
//                        .selectId(R.mipmap.icon_tv_fm_press)
//                        .build(),
//                ChildChannelFragment.newInstance(TYPE_RADIO, (ArrayList<FChannel>) response.getAudioChannel()));
        mViewPager.setAdapter(mAdapter);
        mTabLayout.setupWithViewPager(mViewPager, true);
        setupTabContainer(mAdapter, mTabLayout);
        mViewPager.setScanScroll(false);
        mTabLayout.addOnTabSelectedListener(ChannelFragment.this);

        //////////////////// default video player//////////////////////
        List<FChannel> channels = response.getChannel();
        if (channels != null && channels.size() > 0) {
            mCurChannel = channels.get(0);
            String urls = UrlUtils.linkUrls(Constances.ST_BASE_URL, mCurChannel.getLiveUrl());
            mVideoPlayer.setUp(urls, true, mCurChannel.getChannelName());
            if (isFront) {
                mVideoPlayer.startPlayLogic();
                handler.postDelayed(runnable, 0);

            }
        }
    }


    Runnable runnable=new Runnable(){
        @Override
        public void run() {
            if(mCurChannel!=null) {

                if(isFirstStart) {
                    isFirstStart = false;

                    if (UserManager.isLoginS()) {
                        StatisticsMainInit.tvPlay(UserManager.getInstance().getUser().getPhoneNumber(),
                                mCurChannel.getChannelId(),
                                mCurChannel.getChannelName(), 60);
                    } else {
                        StatisticsMainInit.tvPlay("",
                                mCurChannel.getChannelId(),
                                mCurChannel.getChannelName(), 60);
                    }
                    handler.postDelayed(this, 60000);


                }else{
                    if (UserManager.isLoginS()) {
                        StatisticsMainInit.tvPlay(UserManager.getInstance().getUser().getPhoneNumber(),
                                mCurChannel.getChannelId(),
                                mCurChannel.getChannelName(), 60);
                    } else {
                        StatisticsMainInit.tvPlay("",
                                mCurChannel.getChannelId(),
                                mCurChannel.getChannelName(), 60);
                    }
                    handler.postDelayed(this, 60000);
                }


            }
        }
    };


    @Override
    public void onComplete() {

    }

    @NonNull
    @Override
    public String getUrl() {
        return channelUrl;
    }

    @Override
    public void onError(String error) {
        toast(error);
    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        isFront = true;
        if (null != mVideoPlayer) {
            mVideoPlayer.startPlayLogic();
        }
        handler.postDelayed(runnable, 0);

        return super.onFragmentShow(isFirst, isCallFromResume);
    }

    @Override
    protected void onFragmentUnShowed(boolean isCallFromPause) {
        super.onFragmentUnShowed(isCallFromPause);
        isFront = false;
        if (null != mVideoPlayer) {
            mVideoPlayer.onVideoPause();
        }
        handler.removeCallbacks(runnable);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMessage msg) {
        if (msg.getKey() == KEY_CHANGE_CHANNEL) {
            FChannel channel = (FChannel) msg.getMessage();
            int flags = msg.getFlags();
            JLog.e("LiveUrl: " + channel.getLiveUrl() + " \nChannelId: " + channel.getChannelId() +
                    " \nCurChannelUrl: " + mCurChannel.getLiveUrl() + " \nCurChannelId: " + mCurChannel.getChannelId());

            if (mCurChannel != null && !TextUtils.equals(mCurChannel.getChannelId(), channel.getChannelId())) {
                mCurChannel = channel;
                String urls = UrlUtils.linkUrls(Constances.ST_BASE_URL, mCurChannel.getLiveUrl());
                mVideoPlayer.setUp(urls, true, mCurChannel.getChannelName());
                mVideoPlayer.startPlayLogic();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        GSYVideoManager.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
        if (null != mVideoPlayer) {
            mVideoPlayer.onVideoPause();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mBind != null) mBind.unbind();
        GSYVideoManager.releaseAllVideos();
        handler.removeCallbacks(runnable);

        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onBackPressed() {
        if (StandardGSYVideoPlayer.backFromWindowFull(getContext())) {
            actionToPortrait();
            return true;
        }
        return super.onBackPressed();
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        if (mAdapter != null) {
            int position = tab.getPosition();
            if (tab.getCustomView() != null) {
                setCustomTabView(true, mAdapter.getTab(position), tab.getCustomView());
            }
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        if (mAdapter != null) {
            int position = tab.getPosition();
            if (tab.getCustomView() != null) {
                setCustomTabView(false, mAdapter.getTab(position), tab.getCustomView());
            }
        }
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    private static class TabItem {
        private String title;
        @IdRes
        private int defaultId;
        @IdRes
        private int selectId;

        String getTitle() {
            return title;
        }

        int getDefaultId() {
            return defaultId;
        }

        int getSelectId() {
            return selectId;
        }

        int getTabTextColor() {
            return Color.parseColor("#222222");
        }

        int getTabSelectedTextColor() {
            return Color.parseColor("#F22200");
        }

        private TabItem(Builder builder) {
            title = builder.title;
            defaultId = builder.defaultId;
            selectId = builder.selectId;
        }

        public static final class Builder {
            private String title;
            private int defaultId;
            private int selectId;

            Builder() {
            }

            Builder title(String val) {
                title = val;
                return this;
            }

            Builder defaultId(int val) {
                defaultId = val;
                return this;
            }

            Builder selectId(int val) {
                selectId = val;
                return this;
            }

            public TabItem build() {
                return new TabItem(this);
            }
        }
    }

    /**
     * view pager适配器
     */
    private static class LocalPagerAdapter extends FragmentPagerAdapter {
        private SparseArray<TabItem> tabs = new SparseArray<>();
        private SparseArray<Fragment> fragments = new SparseArray<>();

        LocalPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        void addFragment(int position, TabItem tab, Fragment fragment) {
            tabs.put(position, tab);
            fragments.put(position, fragment);
        }

        SparseArray<TabItem> getTabs() {
            return tabs;
        }

        TabItem getTab(int index) {
            return tabs.get(index);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return getTab(position).getTitle();
        }
    }

    public static class ChildChannelFragment extends Fragment {

        private int mType;
        private ArrayList<FChannel> mData;

        public static ChildChannelFragment newInstance(int type, ArrayList<FChannel> data) {
            Bundle args = new Bundle();
            args.putInt(KEY_TYPE, type);
            args.putParcelableArrayList(KEY_DATA, data);
            ChildChannelFragment fragment = new ChildChannelFragment();
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (getArguments() != null) {
                mType = getArguments().getInt(KEY_TYPE);
                mData = getArguments().getParcelableArrayList(KEY_DATA);
            }
        }

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            final RecyclerView rootView = new RecyclerView(getContext());
            rootView.setLayoutManager(new LinearLayoutManager(getContext()));
            rootView.addItemDecoration(new RBaseItemDecoration(2));
            return rootView;
        }

        @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            final RecyclerView rootView = (RecyclerView) view;
            final ItemAdapter adapter = ItemAdapter.create(getContext());
            rootView.setAdapter(adapter);

            adapter.setNewData(mData);

            adapter.setOnItemClickListener((_adapter, view1, position) -> {
                FChannel item = adapter.getItem(position);
                if (item != null) {
                    for (int i = 0; i < adapter.getData().size(); i++) {
                        if (!TextUtils.equals(adapter.getData().get(i).getChannelId(), item.getChannelId())) {
                            adapter.getData().get(i).setChoice(false);
                        } else {
                            item.setChoice(true);
                        }
                    }
                    adapter.notifyDataSetChanged();

                    EventMessage message = new EventMessage.Builder()
                            .key(KEY_CHANGE_CHANNEL)
                            .message(item)
                            .flags(mType)
                            .build();
                    EventBus.getDefault().post(message);
                }
            });
        }
    }

    private static class ItemAdapter extends BaseQuickAdapter<FChannel, BaseViewHolder> {
        private WeakReference<Context> reference;

        public static ItemAdapter create(Context context) {
            return new ItemAdapter(R.layout.item_child_channel, context);
        }

        private ItemAdapter(int layoutResId, Context context) {
            super(layoutResId);
            reference = new WeakReference<>(context);
            openLoadAnimation();
        }

        @Override
        protected void convert(@NonNull BaseViewHolder helper, FChannel item) {
            Context context = reference.get();
            helper.setText(R.id.title, item.getChannelName());
            helper.setTextColor(R.id.title, item.isChoice() ? ContextCompat.getColor(context, R.color.colorBlack22)
                    : ContextCompat.getColor(context, R.color.colorGray98));
            helper.setVisible(R.id.flags, item.isChoice());
        }
    }

    private static List<FChannel> elementAtSelected(List<FChannel> channels, @IntRange(from = 0) int index) {
        if (channels.size() <= index) return channels;
        for (int i = 0; i < channels.size(); i++) {
            channels.get(i).setChoice(index == i);
        }
        return channels;
    }

    private void setupTabContainer(LocalPagerAdapter adapter, TabLayout tabLayout) {
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(getCustomTabView(adapter.getTab(i)));
                LinearLayout ll = (LinearLayout) tabLayout.getChildAt(0);
                ll.setDividerPadding(30);
                ll.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
                ll.setDividerDrawable(ContextCompat.getDrawable(getContext(), R.drawable.layout_divider_vertical));
            }
        }

        ////////////////////// 默认第一个 //////////////////
        if (tabLayout.getTabCount() > 0) {
            TabLayout.Tab tab = tabLayout.getTabAt(0);
            if (tab != null) {
                View customView = tab.getCustomView();
                if (customView != null) {
                    setCustomTabView(true, adapter.getTab(0), customView);
                }
            }
        }
    }

    private View getCustomTabView(TabItem tab) {
        @SuppressLint("InflateParams") View view = LayoutInflater.from(getContext()).inflate(R.layout.tab_item, null);
        setCustomTabView(false, tab, view);
        return view;
    }

    private void setCustomTabView(boolean isSelected, TabItem tab, View tabView) {
        ImageView iv = tabView.findViewById(R.id.tab_img);
        TextView tv = tabView.findViewById(R.id.tab_text);
        tv.setText(tab.getTitle());
        tv.setTextColor(isSelected ? tab.getTabSelectedTextColor() : tab.getTabTextColor());
        iv.setImageResource(isSelected ? tab.getSelectId() : tab.getDefaultId());
    }
}
